package mysql

import (
	
	"fmt"
	"time"

	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	"bluebell/setting"
	"github.com/spf13/viper"
	
)
 
var (
	DB *gorm.DB
)

func Init() (err error){
	newLogger := logger.New(
		zap.NewStdLog(zap.L()), // 写入到zap日志
		logger.Config{
		  SlowThreshold:              time.Second,   // Slow SQL threshold
		  LogLevel:                   logger.Silent, // Log level
		  IgnoreRecordNotFoundError: true,           // Ignore ErrRecordNotFound error for logger
		  ParameterizedQueries:      true,           // Don't include params in the SQL log
		  Colorful:                  false,          // Disable color
		},
	  )

	// dsn := "user:pass@tcp(113.44.165.94:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		setting.Conf.User,
		setting.Conf.PasswordSql,
		setting.Conf.HostSql,
		setting.Conf.PortSql,
		setting.Conf.DBname,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable:true,
		},
		Logger : newLogger,
	})
	
	sqldb,_ := db.DB()
	//设置连接池中空闲连接的最大数量
	sqldb.SetMaxIdleConns(viper.GetInt("mysql.setmaxidle_conns")) // 例如设置为10
    // 设置最大打开的连接数
    sqldb.SetMaxOpenConns(viper.GetInt("mysql.setmaxopen_conns")) // 例如设置为100
	DB = db
	return
}